package tcp.voicedic;

import java.io.*;
import java.net.*;
import java.util.ArrayList;
import java.util.List;

import android.app.ListActivity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Environment;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class VoiceDic extends ListActivity {
	
	private static final String MUSIC_PATH = "/Music/";
	private static File musicDirectory = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + MUSIC_PATH);
	public static MediaPlayer mp = new MediaPlayer();
	public static  List<String> songs = new ArrayList<String>();
	public static  List<Columnist> columnists = new ArrayList<Columnist>(); 
	
    /** Called when the activity is first created. */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_list);        
		try {
			readHtml();
		} catch (Exception e) {
			Toast.makeText(VoiceDic.this,"EXCEPTION", Toast.LENGTH_SHORT).show();
		}
	
        fillScreen();

    }    

    /* (non-Javadoc)
	 * @see android.app.Activity#onResume()
	 */
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
	}

	/** Called when the user goes to the main Android menu */
    @Override
    protected void onStop(){
    	super.onStop();
    	mp.stop();
    }
    
    /** Fills the screen with a list. */
    private void fillScreen(){
    	createSongsList();
    	
    	if (songs.isEmpty()){
   		//No music was found
    	}
     	setListAdapter(new ArrayAdapter<String>(this, R.layout.item_list, songs));
        getListView().setTextFilterEnabled(true);
	
		Toast.makeText(VoiceDic.this,"Hi! VoiceDic", Toast.LENGTH_SHORT).show();
        
    }
    
    /** Creates a list with the name of the songs. */
    private void createSongsList(){
    	String mState = Environment.getExternalStorageState();
    	if (!musicDirectory.exists()){
    		musicDirectory.mkdir();
    	}
    	
    	String[] allFilesInDir =  musicDirectory.list();
    	songs.clear();
    	if (Environment.MEDIA_MOUNTED.equals(mState) || Environment.MEDIA_MOUNTED_READ_ONLY.equals(mState)) {
    		for (int i = 0; i<allFilesInDir.length; i++){
        		if (allFilesInDir[i].endsWith(".mp3")){
        			allFilesInDir[i] = allFilesInDir[i].substring(0, allFilesInDir[i].length() - 4);
        			songs.add(allFilesInDir[i]);        			
        		}
    		}
    	}
    	
    	else {
    	//error on accessing SD card
    	}   	
    }
    
    /** Detects when the user selected an item on the list */
    protected void onListItemClick(ListView l, View v, int position, long id) {
    	playSong(songs.get(position) + ".mp3"); 
    }
    
    /** Plays the song selected by the user */
    public static void playSong(String musicName){
    	try{
    		mp.reset();
    		mp.setDataSource(musicDirectory.getAbsolutePath() + "/" + musicName);
    		mp.prepare();
    		mp.start();
    		}
    	
    	catch(IOException e){
    		//Could not read the file.
    	}
    }
    
    public boolean onCreateOptionsMenu (Menu menu){
    	 MenuInflater inflater = getMenuInflater();
    	 inflater.inflate(R.menu.main_menu, menu);
    	 return true;
    }
    
    public boolean onOptionsItemSelected(MenuItem item){
    	switch(item.getItemId()){
    	case R.id.find_words:
    		try {
				findWords();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
    		return true;

    	default:
    		return super.onOptionsItemSelected(item);
    	}
    }

    private void findWords() {    	
    	    	startActivityForResult(new Intent(this, WordSearch.class), 0);   	
    }
    
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
	}
    
	private void readHtml ()throws Exception{
		 
	        URL folhaURL = new URL("http://www1.folha.uol.com.br/colunas");
	        URLConnection folhaConnection = folhaURL.openConnection();
	        BufferedReader in = new BufferedReader(
	                                new InputStreamReader(
	                                folhaConnection.getInputStream()));
	        String inputLine;
	        String dataMarker = ("<div class=\"openBox columnList\">");
	    	String columnistName;
	    	String lastColumnName;
	    	String columnistPageLink;
	    	String columnistImageLink;
	    	
	    	int i = 0;
	    	
	    	
	        while ((inputLine = in.readLine()) != null)
	        {
	        	if (inputLine.equals(dataMarker))
				{	        	
				inputLine = in.readLine();
				columnistName = inputLine.substring( 23, inputLine.lastIndexOf('<'));
				//Toast.makeText(VoiceDic.this,"-"+columnistName+"-", Toast.LENGTH_SHORT).show();
				
				inputLine = in.readLine();				
				columnistPageLink = "http://www1.folha.uol.com.br" + inputLine.substring( 9 , inputLine.indexOf("\"", 10));
				//Toast.makeText(VoiceDic.this,"-"+columnistPageLink+"-", Toast.LENGTH_SHORT).show();
				

				columnistImageLink = inputLine.substring( inputLine.indexOf("h", inputLine.indexOf("\"", 10)+1) -1, inputLine.indexOf("alt") -1);						
				columnists.add(new Columnist(columnistName,"ULTIMA COLUNA",columnistPageLink,columnistImageLink));
				Toast.makeText(VoiceDic.this,columnists.get(i).getColumnistName(), Toast.LENGTH_SHORT).show();
				i++;
				}
	        	
	        }
	        
	        in.close();
	        
	    
		Toast.makeText(VoiceDic.this,"Ler HTML", Toast.LENGTH_SHORT).show();
	}
	

	
}